import { useEffect, useState } from 'react';
import { Table, Tag, Image, Button, Space, Input, Popconfirm, message } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import dayjs from 'dayjs';
import { HappyProvider } from '@ant-design/happy-work-theme';
import { DeleteFilled } from "@ant-design/icons"
import { getAllFood, deleteOne } from "@/apis/admin/food"
import { useNavigate } from 'react-router-dom'
const base_url = import.meta.env.VITE_APP_URL
interface DataType {
    _id: string;
    title: string;
    publish_time: number;
    type: string;
    texttual: string
    Cover_img: string
}
const typechoose = (type: string) => {
    switch (type) {
        case '0':
            return {
                text: '主菜',
                color: 'red'
            }
        case '1':
            return {
                text: '汤品',
                color: 'blue'
            }
        case '2':
            return {
                text: '甜点/烘焙',
                color: 'green'
            }
        case '3':
            return {
                text: '饮品',
                color: 'yellow'
            }
        default:
            return {
                text: '',
                color: ''
            }
    }
}



const Food = () => {
    const [total, setTotal] = useState(0)
    const [Currentpage, setCurrentpage] = useState(1)
    const [FoodList, setFoodList] = useState<any>([])
    const [types, settypes] = useState('4')
    const [keyword, setkeyword] = useState('')
    const [orders, setoreder] = useState('desc')
    const native = useNavigate()
    const columns: TableColumnsType<DataType> = [
        {
            title: '名称',
            dataIndex: 'title',
            align: "center",
            width: "15%",
            ellipsis: true,
        },
        {
            title: "图片",
            align: "center",
            width: "15%",
            dataIndex: 'Cover_img',
            render: (_, { Cover_img }) => {

                return (
                    <Image src={base_url + Cover_img} width={"110px"} height={"65px"} alt="" />
                )
            }
        },
        {
            title: "类型",
            dataIndex: 'type',
            align: "center",
            width: "10%",
            filters: [
                {
                    text: '主菜',
                    value: '0',
                },
                {
                    text: '汤品',
                    value: '1',
                },
                {
                    text: "甜点/烘焙",
                    value: "2"
                },
                {
                    text: "饮品",
                    value: "3"
                }

            ],
            render: (_, { type }) => {
                const res = typechoose(type)
                return (
                    <Tag color={res.color}>{res.text}</Tag>
                )
            },
            filterMultiple: false,
            onFilter: (value, record) => {

                return record.type === value
            },

        },
        {
            title: '时间',
            dataIndex: 'publish_time',

            defaultSortOrder: 'descend',
            render: (_, { publish_time }) => {
                return (
                    <div>{dayjs(publish_time).format('YYYY-MM-DD')}</div>
                )
            },
            sorter: (a, b) => a.publish_time - b.publish_time,
        },

        {
            title: '描述',
            dataIndex: 'texttual',
            align: "center",
            ellipsis: true,
            width: "30%"
        },
        {
            title: '操作',
            align: "center",
            width: "10%",
            render: (_, { _id }) => {
                console.log(_.title)
                return (
                    <Space size={"small"}>
                        <a style={{ color: 'skyblue' }} onClick={() => {
                            native(`/detaile/${_id}`)
                        }}>查看</a>

                        <HappyProvider>
                            <Popconfirm
                                title={"删除：" + _.title}
                                description="确认删除吗?"
                                onConfirm={() => confirm(_id)}
                                onCancel={cancel}
                                okText="确认"
                                cancelText="取消"
                            >
                                <Button type="dashed" icon={<DeleteFilled style={{ color: 'red' }} />}></Button>

                            </Popconfirm>
                        </HappyProvider>
                    </Space>
                )
            }
        }
    ];
    const confirm = async (e: any) => {
        console.log(e);
        const res = await deleteOne(e)
        if (res.status === 200) {
            message.success("删除成功")
            if (Currentpage !== 1 && FoodList.length == 1) {
                setCurrentpage(Currentpage - 1)

            } else {
                GetData(Currentpage * 5 - 5, keyword)
            }
        }
    };

    const cancel = (e: any) => {
        console.log(e);
    };
    const onChange: TableProps<DataType>['onChange'] = (pagination, filters, sorter: any, extra) => {
        pagination
        extra
        if (!sorter.order) {
            setoreder('desc')
        } else {
            if (sorter.order === 'descend') {
                setoreder("desc")
            } else {
                setoreder('asc')
            }
        }
        if (!filters.type?.[0]) {
            settypes('4')
        } else {
            settypes(filters.type?.[0] as string)
        }
    };
    const GetData = async (skip = 0, keyword = '') => {
        const result: any = await getAllFood(skip, types, keyword, orders)
        console.log(result, 'ssssss')
        setTotal(result.count[0] ? result.count[0].total : 0)
        setFoodList([...result.data])

    }
    const Search = () => {
        setCurrentpage(1)
        GetData(0, keyword)
    }
    const GETALL = () => {
        setkeyword('')
        GetData(0, '')
    }
    useEffect(() => {
        GetData(Currentpage * 5 - 5, keyword)
    }, [Currentpage, types, orders])
    return (
        <div style={{ width: "100%" }}>

            <Space size={"middle"} style={{ margin: '5px 0' }}>
                <Input value={keyword} onChange={(e) => setkeyword(e.target.value)} />
                <HappyProvider>
                    <Button type="primary" onClick={Search}>搜索</Button>
                </HappyProvider>
                <HappyProvider>
                    <Button type="primary" onClick={GETALL}>全部</Button>
                </HappyProvider>

            </Space>
            <Table
                rowKey={"_id"}
                columns={columns}
                dataSource={FoodList}
                onChange={onChange}
                showSorterTooltip={{ target: 'sorter-icon' }}
                pagination={{
                    showTotal: () => {
                        return `共${total}条`
                    },
                    current: Currentpage,
                    defaultCurrent: 1,
                    total: total,
                    defaultPageSize: 5,
                    showSizeChanger: false,
                    onChange: (page) => {
                        setCurrentpage(page)
                    }

                }}
            />
        </div>
    )
}

export default Food;